package com.example.weather_news.adapter;

/**
 * Created by 逝 on 2017/06/11.
 */

//public class Adapter_News {
//}

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.weather_news.R;
import com.example.weather_news.http.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;

public class Adapter_News extends BaseAdapter {

    private JSONArray arrays = new JSONArray();
    private Context context;
    private LayoutInflater layoutInflater;

    public Adapter_News(Context context) {
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    public void setData(JSONArray arrays) {
        this.arrays = arrays;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (arrays.length() == 0) {
            return 0;
        }
        return arrays.length();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder = null;
        if (view == null) {
            holder = new ViewHolder();
            view = layoutInflater.inflate(R.layout.lv_item, null);
            holder.ivItemNewslist = (ImageView) view.findViewById(R.id.iv_item_newslist);
            holder.tvItemTitle = (TextView) view.findViewById(R.id.tv_item_title);
            holder.tvItemFrom = (TextView) view.findViewById(R.id.tv_item_from);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        try {
            String url = arrays.getJSONObject(position).getString("pic");
            Log.e("url", url);
            if (url==null) {
                holder.ivItemNewslist.setBackgroundResource(R.mipmap.ic_launcher_round);
            } else {
                HttpRequest.requestImg(url, holder.ivItemNewslist);
            }
            holder.tvItemTitle.setText(arrays.getJSONObject(position).getString("title"));
            holder.tvItemFrom.setText(arrays.getJSONObject(position).getString("src"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return view;
    }

    protected class ViewHolder {
        private ImageView ivItemNewslist;
        private TextView tvItemTitle;
        private TextView tvItemFrom;
    }
}

